package com.lzj.springcloudzuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class TokenFilter extends ZuulFilter {

    // 过滤器类型 pre表示在请求之前进行拦截
    @Override
    public String filterType() {
        return "pre"; //在请求之前过滤
    }

    // 过滤器的执行顺序。当请求在一个阶段的时候存在多个多个过滤器时，
    // 需要根据该方法的返回值依次执行
    @Override
    public int filterOrder() {
        return 0;
    }

    // 判断过滤器是否生效
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String userToken = request.getParameter("userToken");

        if(StringUtils.isEmpty(userToken)) {
            //如果userToken为空，则拦截
            ctx.setSendZuulResponse(false); //表示拦截掉
            ctx.setResponseBody("userToken is null");
            ctx.setResponseStatusCode(401);
            return null;
        }

        //否则，执行正常服务逻辑
        return null;
    }
}
